﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Lon.Util
{
    public class HashHelper
    {
        public static string GetTextHash(string value)
        {
            byte[] buffer = Encoding.Default.GetBytes(value);

            HashAlgorithm hashAlgo = MD5.Create();

            byte[] hashBuffer = hashAlgo.ComputeHash(buffer);

            return HexToStr(hashBuffer);
        }

        public static string GetFileHash(string fileName)
        {
            HashAlgorithm hashAlgo = MD5.Create();

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = hashAlgo.ComputeHash(fs);
                return HexToStr(buffer);
            }            
        }

        public static string HexToStr(byte[] buffer)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                sb.Append(buffer[i].ToString("X2"));
            }

            return sb.ToString();
        }

    }
}
